import { getUserInfo } from '@/common/api/user.js';
import { BASE_URL } from '@/common/utils/request.js';

export const isLogin = () => {
  const userInfo = uni.getStorageSync('userInfo');
  if (!userInfo || !userInfo.id) {
    return false;
  }
  return true;
};

export const checkLogin = () => {
  if (!isLogin()) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/login/pre-login'
      });
    }, 1500);
    return false;
  }
  return true;
};

export const checkUserInfo = () => {
  if (!checkLogin()) {
    return false;
  }
  const userInfo = uni.getStorageSync('userInfo');
  if (
    !userInfo.nickName ||
    !userInfo.unit ||
    !userInfo.bossName ||
    !userInfo.researchGroup
  ) {
    uni.showModal({
      title: '提示',
      icon: 'none',
      content: '请先完善个人信息',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({
            url: '/pages/user/edit/edit'
          });
        }
      }
    });
    return false;
  }

  return true;
};

// 通过接口获取用户信息
export const onGetUserInfo = async () => {
  if (!isLogin()) {
    return false;
  }
  const userInfo = uni.getStorageSync('userInfo');

  getUserInfo(userInfo.id)
    .then((res) => {
      uni.setStorageSync('userInfo', res.data.data);
      return res.data.data;
    })
    .catch((err) => {
      console.error('获取用户信息失败:', err);
      return null;
    });
};

// 获取第一张图片
export const getFirstImage = (imageListStr) => {
  if (imageListStr) {
    return `${BASE_URL}${imageListStr.split(',')[0]}`;
  }
  return '/static/img/category/3.png';
};
